package generator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Attribute;
import org.dom4j.Element;

/**
 * decorator that eases access to an OO.o image element
 */
public class OOImage {
	public OOImage(Element element) {
		super();
		subject = element;
	}

	private Attribute getNameAttribute() {
		return subject.attribute("name");
	}

	public String getName() {
		if (null == getNameAttribute()) {
			return null;
		}
		return getNameAttribute().getText();
	}

	public void setName(String s) {
		Attribute name = getNameAttribute();
		name.setData(s);
	}

	public Attribute getHrefAttribute() {
		return subject.attribute("href");
	}

	public String getHref() {
		if (null == getHrefAttribute()) {
			return null;
		}
		return getHrefAttribute().getData().toString();
	}

	public String getFilename() {
		Attribute href = getHrefAttribute();
		return href.getData().toString().substring(10);
	}

	public void setFilename(String s) {
		Attribute href = getHrefAttribute();
		if (!s.startsWith("#Pictures/")) {
			s = "#Pictures/" + s;
		}
		href.setData(s);
	}

	public Attribute getWidthAttribute() {
		return subject.attribute("width");
	}

	public Attribute getHeightAttribute() {
		Attribute h = subject.attribute("height");
		if (null==h && log.isDebugEnabled()) {
			log.warn("didn't find a height attribute");
		}
		return h;
	}

	public Element getAltTextElement() {
		return subject.element("desc");
	}

	public String getAltText() {
		if (null == getAltTextElement()) {
			return null;
		}
		return getAltTextElement().getTextTrim();
	}

	public boolean isTagged() {
		if (null == getAltText()) {
			return false;
		}
		if (getAltText().startsWith("#")) {
			return true;
		}
		return false;
	}

	public String getTag() {
		if (!isTagged()) {
			return null;
		}
		return getAltText().substring(1, getAltText().length() - 1);
	}

	public String toString() {
		String toStr = getName() + " [" + getFilename() + "]";
		return toStr;
	}

	private Element subject;

	private final static Log log = LogFactory.getLog(OOImage.class);

}
